package ca.uwindsor;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AlertDialogLogin extends Activity implements OnClickListener {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.alertlogin);

		/*Context mContext = getApplicationContext();
		Dialog dialog = new Dialog(mContext);
		
		dialog.setContentView(R.layout.alertlogin);
		dialog.setTitle("Create a password");
		
		dialog.show();*/
		
		setContentView(R.layout.login);

		
		Button login_but = (Button) findViewById(R.id.but_login);
		
		
		login_but.setOnClickListener(this);
		
		
		//Create all Databases.
		try{
		createDB();
		}catch(SQLiteException e){
			
		}
		final MyDBAdapter db = new MyDBAdapter(this);
		db.setDATABASE_TABLE("users");
		db.open();
		
		Cursor ret = db.getAllEntries();
		int flag = ret.getCount();
		
		//if database is empty show dialog
		if(flag==0){
			
			showDialog(1);
			
		}
		
	db.close();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
        case 1:
		LayoutInflater inflater =
				(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View layout = 
				inflater.inflate(R.layout.alertlogin, null);

		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setView(layout);
		alert.setTitle("Create a password");
		
		alert.setCancelable(false);
		
		Button add_but = (Button) layout.findViewById(R.id.but_addPass);
		
		add_but.setOnClickListener(new View.OnClickListener() {
		
		//alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
			//public void onClick(DialogInterface dialog, int whichButton) {
				
			//}

			@SuppressWarnings("static-access")
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditText password = (EditText)layout.findViewById(R.id.txtPass);
				EditText hint = (EditText)layout.findViewById(R.id.txtHint);
				EditText passwordCnf = (EditText)layout.findViewById(R.id.txtPassCnf);
				
				if(password.getText().toString().equals(passwordCnf.getText().toString())){
					
					addPassword(password,hint);
					
					Intent login = new Intent("ca.uwindsor.ALERTDIALOGLOGIN");
					login.setFlags(login.FLAG_ACTIVITY_CLEAR_TOP); //prevents the user from going back to the dialog
					startActivity(login);
				
				}else if((password.getText().toString().trim().equals(""))
						||(hint.getText().toString().trim().equals("")))
						{
					//TextView noMatch = new TextView(getApplicationContext());
					TextView noMatch = (TextView)layout.findViewById(R.id.lblNoMatch);
					noMatch.setText("Fields cannot be blank.");
				}
				else{
					
					//TextView noMatch = new TextView(getApplicationContext());
					TextView noMatch = (TextView)layout.findViewById(R.id.lblNoMatch);
					noMatch.setText("Passwords do not match.");
					
					
				}
			}
		});

		AlertDialog passwordDialog = alert.create();
        return passwordDialog;
		}
		return null;
	}
	
	//Creates all Database tables.
	protected void createDB(){
		
		final MyDBAdapter db = new MyDBAdapter(this);
		
		String DATABASE_CREATE = "create table " + 
	    	    "users" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "password" + " text not null, " +
	    	    "hint" + " text not null, "+
	    	    "prev_GPA" + " text,"+
	    	    "credit_com" + " text"+ ");";
		
		db.setDATABASE_CREATE(DATABASE_CREATE);
		
		db.open();
		db.setDATABASE_TABLE("users");
		
		Cursor ret = db.getAllEntries();
		int flag = ret.getCount();
		
		if(flag==0){
			//CREATE ALL OTHER DATABASES
		String DB_CREATE_TABLE = "create table " + 
	    	    "semester" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "Name" + " text not null, " +
	    	    "StartDate" + " text not null, "+
	    	    "EndDate" + " text not null, "+
	    	    "Comments" + " text" +
	    	    		");";
		
		db.executeSQL(DB_CREATE_TABLE);
		
		DB_CREATE_TABLE = "create table " + 
	    	    "courses" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "sem_name" + " text not null, " +
	    	    "course_code" + " text not null, "+
	    	    "course_name" + " text not null, "+
	    	    "credit" + " integer not null," +
	    	    "FOREIGN KEY(sem_name) REFERENCES semester(sem_name)"+
	    	    		");";
		
		db.executeSQL(DB_CREATE_TABLE);
		
		DB_CREATE_TABLE = "create table " + 
	    	    "class_schedule" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "sem_name" + " text not null, " +
	    	    "course_code" + " text not null, " +
	    	    "Day" + " text not null, "+
	    	    "StartTime" + " text not null, "+
	    	    "EndTime" + " text not null, " +
	    	    "FOREIGN KEY(sem_name) REFERENCES semester(sem_name),"+
	    	    "FOREIGN KEY(course_code) REFERENCES courses(course_code)"+
	    	    		");";
		
		db.executeSQL(DB_CREATE_TABLE);
		
		DB_CREATE_TABLE = "create table " + 
	    	    "event_schedule" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "Date" + " text not null, " +
	    	    "course_code" + " text not null, "+
	    	    "StartTime" + " text not null, "+
	    	    "EndTime" + " text not null, " +
	    	    "Type" + " text not null, " +
	    	    "Comments" + " text, " +
	    	    "FOREIGN KEY(course_code) REFERENCES courses(course_code)"+
	    	    		");";
		
		db.executeSQL(DB_CREATE_TABLE);
		
		DB_CREATE_TABLE = "create table " + 
	    	    "marks" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "course_code" + " text not null, " +
	    	    "marks" + " real not null, "+
	    	    "total_marks" + " real not null, "+
	    	    "weightage" + " real not null," +
	    	    "marks_ob" + " real not null," +
	    	    "FOREIGN KEY(course_code) REFERENCES courses(course_code)"+
	    	    		");";
		
		db.executeSQL(DB_CREATE_TABLE);
		
		DB_CREATE_TABLE = "create table " + 
	    	    "grading" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "letter_grade" + " text not null, " +
	    	    "grade_point" + " integer not null, "+
	    	    "start_range" + " integer not null, "+
	    	    "end_range" + " integer not null"+
	    	    		");";
		
		db.executeSQL(DB_CREATE_TABLE);
		
		DB_CREATE_TABLE = "create table " + 
	    	    "tasks" + " (" + "_id" + 
	    	    " integer primary key autoincrement, " +
	    	    "description" + " text not null"+
	    	    		");";
		
		db.executeSQL(DB_CREATE_TABLE);
		
		//store grades in database
		String[] letterGrade = {"A+","A","A-","B+","B","B","C+","C","C-","D+","D","D-","F","F-"};
		Integer[] start_range = {93, 86, 80, 77, 73,70,67,63,60,57,53,50,35,0};
		Integer[] end_range = {101,93,86,80,77,73,70,67,63,60,57,53,50,35};
		
		db.setDATABASE_TABLE("grading");
		for(int i=0; i<=13; i++){
		ContentValues newValues = new ContentValues();
		newValues.put("letter_grade", letterGrade[i]);
		newValues.put("grade_point", 13-i);
		newValues.put("start_range", start_range[i]);
		newValues.put("end_range", end_range[i]);
		db.insertEntry(newValues);
		}
		}
		db.close();
		
	}
	
	protected void addPassword(EditText password, EditText hint){
		final MyDBAdapter db = new MyDBAdapter(this);
		db.open();
		db.setDATABASE_TABLE("users");
		
		ContentValues newValues = new ContentValues();
		
		newValues.put("password", password.getText().toString());
		
		newValues.put("hint", hint.getText().toString());
		
		db.insertEntry(newValues);
		
		db.close();
		
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
		case R.id.but_login:
			
		final MyDBAdapter db = new MyDBAdapter(getApplicationContext());
		db.setDATABASE_TABLE("users");
		db.open();
		
		Cursor ret = db.getAllEntries();
		ret.moveToFirst();
		String password = ret.getString(1);
		
		EditText txtPass = (EditText)findViewById(R.id.txtLogin);
		if(txtPass.getText().toString().equals(password)){
			//Go to menu
				
			startActivity(new Intent("ca.uwindsor.WELCOMEMENU"));
			
		}else{
			//Alert the user
			final AlertDialog.Builder alert = new AlertDialog.Builder(this);
			
			alert.setMessage("Wrong password. Try again.");
		
			alert.setNegativeButton("Go Back", new DialogInterface.OnClickListener(){

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					//do nothing
					EditText txtPass = (EditText)findViewById(R.id.txtLogin);
					txtPass.setText("");
				}
				
			});
			alert.show();
			
		}db.close(); break;
		
		default:startActivity(new Intent("ca.uwindsor.MENU"));break;
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}
}

